<?php
global $_GPC, $_W;
$GLOBALS['frames'] = $this->getMainMenu();
$operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
$type=empty($_GPC['type']) ? 'all' :$_GPC['type'];
$state=$_GPC['state'];
$pageindex = max(1, intval($_GPC['page']));
$pagesize=10;
$where=' WHERE  a.uniacid=:uniacid';
$data[':uniacid']=$_W['uniacid'];
if(isset($_GPC['keywords'])){
    $op=$_GPC['keywords'];
    $where.=" and a.realname LIKE  concat('%', :name,'%') ";    
    $data[':name']=$op;
    $type='all';
}
if($type!='all'){   
 $where.= " and a.state=$state"; 
}
$sql="SELECT a.*,b.username,b.avatar,b.phone as cusphone FROM ".tablename('zh_gjw_cashlist') .  " a"  . " left join " . tablename("zh_gjw_register") . " b on a.u_id=b.id". $where." ORDER BY a.applytime DESC";
$total=pdo_fetchcolumn("SELECT count(*) FROM ".tablename('zh_gjw_cashlist') .  " a"  . " left join " . tablename("zh_gjw_register") . " b on a.u_id=b.id". $where,$data);
// $list=pdo_fetchall($sql,$data);
$select_sql =$sql." LIMIT " .($pageindex - 1) * $pagesize.",".$pagesize;
$list=pdo_fetchall($select_sql,$data);
$pager = pagination($total, $pageindex, $pagesize);


if($operation=='adopt'){//审核通过
            /*function getaccess_token($_W){
                $res=pdo_get('zh_gjw_system',array('uniacid'=>$_W['uniacid']));
                $appid=$res['appid'];
                $secret=$res['appsecret'];
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret."";
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL,$url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
                $data = curl_exec($ch);
                curl_close($ch);
                $data = json_decode($data,true);
                return $data['access_token'];
            }*/
            function set_msg($_W,$_GPC){
                  //$access_token = getaccess_token($_W);
                  $ress=pdo_get('zh_gjw_system',array('uniacid'=>$_W['uniacid']));
                  $cashlist=pdo_get('zh_gjw_cashlist',array('id'=>$_GPC['id']));
                  $openid=pdo_get('zh_gjw_register',array('id'=>$cashlist['u_id']));
                  $formwork ='{
                      "touser": "'.$openid["openid"].'",
                      "template_id": "'.$ress["templeidapply"].'",
                      "form_id":"'.$cashlist['formid'].'",
                      "data": {
                          "keyword1": {
                              "value": "'.round($cashlist['realcash'],2).'",
                              "color": "#173177"
                          },
                          "keyword2": {
                              "value":"'.$cashlist['applytime'].'",
                              "color": "#173177"
                          },
                          "keyword3": {
                              "value":"提现通过",
                              "color": "#173177"
                          }
                      }  
                  }';
                  $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=".$ress['accessToken']."";
                  $ch = curl_init();
                  curl_setopt($ch, CURLOPT_URL,$url);
                  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
                  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
                  curl_setopt($ch, CURLOPT_POST,1);
                  curl_setopt($ch, CURLOPT_POSTFIELDS,$formwork);
                  $data = curl_exec($ch);
                  curl_close($ch);
                 return $data;
            }
            set_msg($_W,$_GPC);
    $res=pdo_update('zh_gjw_cashlist',array('state'=>2,'cashtime'=>date('Y-m-d H:i:s')),array('id'=>$_GPC['id']));  
    if($res){
        message('审核成功',$this->createWebUrl('applymoney',array()),'success');
    }else{
        message('审核失败','','error');
    }
  
}
if($operation=='reject'){
            /*function getaccess_token($_W){
                $res=pdo_get('zh_gjw_system',array('uniacid'=>$_W['uniacid']));
                $appid=$res['appid'];
                $secret=$res['appsecret'];
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret."";
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL,$url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
                $data = curl_exec($ch);
                curl_close($ch);
                $data = json_decode($data,true);
                return $data['access_token'];
            }*/
            function set_msg($_W,$_GPC){
                  //$access_token = getaccess_token($_W);
                  $ress=pdo_get('zh_gjw_system',array('uniacid'=>$_W['uniacid']));
                  $cashlist=pdo_get('zh_gjw_cashlist',array('id'=>$_GPC['id']));
                  $openid=pdo_get('zh_gjw_register',array('id'=>$cashlist['u_id']));
                  $formwork ='{
                      "touser": "'.$openid["openid"].'",
                      "template_id": "'.$ress["templeidapply"].'",
                      "form_id":"'.$cashlist['formid'].'",
                      "data": {
                          "keyword1": {
                              "value": "'.round($cashlist['realcash'],2).'",
                              "color": "#173177"
                          },
                          "keyword2": {
                              "value":"'.$cashlist['applytime'].'",
                              "color": "#173177"
                          },
                          "keyword3": {
                              "value":"提现被拒",
                              "color": "#173177"
                          }
                      }  
                  }';
                  $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=".$ress['accessToken']."";
                  $ch = curl_init();
                  curl_setopt($ch, CURLOPT_URL,$url);
                  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
                  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
                  curl_setopt($ch, CURLOPT_POST,1);
                  curl_setopt($ch, CURLOPT_POSTFIELDS,$formwork);
                  $data = curl_exec($ch);
                  curl_close($ch);
                 return $data;
            }
            set_msg($_W,$_GPC);
    $res=pdo_update('zh_gjw_cashlist',array('state'=>3,'cashtime'=>date('Y-m-d H:i:s')),array('id'=>$_GPC['id']));
     if($res){
        message('拒绝成功',$this->createWebUrl('applymoney',array()),'success');
    }else{
        message('拒绝失败','','error');
    }
}
if($operation=='delete'){
     $res=pdo_delete('zh_gjw_cashlist',array('id'=>$_GPC['id']));
     if($res){
        message('删除成功',$this->createWebUrl('applymoney',array()),'success');
    }else{
        message('删除失败','','error');
    }

}

if($operation=='adopt2'){
    $id=$_GPC['id'];
    $cashlist=pdo_get('zh_gjw_cashlist',array('id'=>$_GPC['id']));
    $user=pdo_get('zh_gjw_register',array('id'=>$cashlist['u_id']));

////////////////打款//////////////////////
    function arraytoxml($data){
        $str='<xml>';
        foreach($data as $k=>$v) {
            $str.='<'.$k.'>'.$v.'</'.$k.'>';
        }
        $str.='</xml>';
        return $str;
    }
    function xmltoarray($xml) { 
        //禁止引用外部xml实体 
        libxml_disable_entity_loader(true); 
        $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA); 
        $val = json_decode(json_encode($xmlstring),true); 
        return $val;
    } 
    function curl($param="",$url) {
        global $_GPC, $_W;
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init();                                      //初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);                 //抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);                    //设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);            //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);                      //post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);           // 增加 HTTP Header（头）里的字段 
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);        // 终止从服务端进行验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch,CURLOPT_SSLCERT,IA_ROOT . "/addons/zh_gjw/cert/".'apiclient_cert_' . $_W['uniacid'] . '.pem'); //这个是证书的位置绝对路径
        curl_setopt($ch,CURLOPT_SSLKEY,IA_ROOT . "/addons/zh_gjw/cert/".'apiclient_key_' . $_W['uniacid'] . '.pem'); //这个也是证书的位置绝对路径
        $data = curl_exec($ch);                                 //运行curl
        curl_close($ch);
        return $data;
    }  
    $system=pdo_get('zh_gjw_system',array('uniacid'=>$_W['uniacid']));
    $data=array(
        'mch_appid'=>$system['appid'],//商户账号appid
        'mchid'=>$system['mac_id'],//商户号
        'nonce_str'=>rand(1111111111,9999999999),//随机字符串
        'partner_trade_no'=>time().rand(11111,99999),//商户订单号
        'openid'=>$user['openid'],//用户openid
        'check_name'=>'NO_CHECK',//校验用户姓名选项,
        're_user_name'=>$cashlist['realname'],//收款用户姓名
        'amount'=>round($cashlist['realcash'], 2)*100,//金额
        'desc'=>'提现打款',//企业付款描述信息
        'spbill_create_ip'=>$system['ip_address'],//Ip地址
    );
  
    $key=$system['apikey'];///这个就是个API密码。32位的。。随便MD5一下就可以了
   // $key=md5($key);
 	//var_dump($data);die;
    $data=array_filter($data);
    ksort($data);
    $str='';
    foreach($data as $k=>$v) {
        $str.=$k.'='.$v.'&';
    }
    $str.='key='.$key;
    $data['sign']=md5($str);
    $xml=arraytoxml($data);
    $url='https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
    $res=curl($xml,$url);
    $return=xmltoarray($res);
    if($return['result_code']=='SUCCESS'){
      pdo_update('zh_gjw_cashlist',array('state'=>2,'cashtime'=>time()),array('id'=>$id));
      message('审核成功',$this->createWebUrl('applymoney',array()),'success');
    }else{
        if($return['err_code_des']){
            $message=$return['err_code_des'];
        }else{
            $message='请检查证书是否上传正确!';
        }
      message($return['err_code_des'],'','error');
    }
    // print_r($return);
  
////////////////打款//////////////////////

}






include $this->template('web/applymoney');